import 'package:flutter/foundation.dart';
import 'dart:io' show Platform;
import 'package:get/get.dart';
import 'package:tapjoy_offerwall/tapjoy_offerwall.dart';
import '../service/tapjoy_service.dart';

class TapjoyController extends GetxController {
  final TapjoyService _service = TapjoyService.instance;

  final RxBool isConnected = false.obs;
  final RxBool isOfferwallReady = false.obs;
  final RxString defaultPlacementName = 'offerwall_main'.obs;

  @override
  void onInit() {
    super.onInit();
    isConnected.value = _service.isConnected;
    if (!kIsWeb && Platform.isAndroid) {
      // Android 使用你提供的 Placement 名称
      defaultPlacementName.value = 'watchofferwall';
    }

    if (Platform.isIOS){
       // Apple 使用你提供的 Placement 名称
      defaultPlacementName.value = 'BitPlanera-offerWall-Apple';
      
    }
  }

  Future<bool> connect({
    required String sdkKey,
    Map<String, dynamic>? options,
    String? userId,
    VoidCallback? onSuccess,
    void Function(int code, String? error)? onFailure,
    void Function(int code, String? warning)? onWarning,
  }) async {
    // 在连接时携带 userId 等默认选项，避免单独调用 setUserId 引发插件回调空指针
    final Map<String, dynamic> defaultOpts = _service.buildDefaultOptions(
      enableLogging: true,
      // 显式传入 GDPR 相关字段，避免 iOS Tapjoy 的未设置警告
      userConsent: false,
      isBelowConsentAge: false,
      userId: userId,
    );
    final Map<String, dynamic> mergedOptions = <String, dynamic>{
      ...?options,
      ...defaultOpts,
    };

    final ok = await _service.connect(
      sdkKey: sdkKey,
      options: mergedOptions,
      onSuccess: () {
        isConnected.value = true;
        onSuccess?.call();
      },
      onFailure: (code, error) {
        isConnected.value = false;
        onFailure?.call(code, error);
      },
      onWarning: (code, warning) {
        onWarning?.call(code, warning);
      },
    );
    return ok;
  }

  Future<void> prefetchOfferwall({
    String? placementName,
    TJEntryPoint? entryPoint,
  }) async {
    final name = placementName ?? defaultPlacementName.value;
    await _service.ensurePlacement(placementName: name, entryPoint: entryPoint);
    await _service.requestContent(name);
    await refreshOfferwallReady(placementName: name);
  }

  Future<void> refreshOfferwallReady({String? placementName}) async {
    final name = placementName ?? defaultPlacementName.value;
    try {
      final p = await _service.ensurePlacement(placementName: name);
      isOfferwallReady.value = await p.isContentReady();
    } catch (_) {
      isOfferwallReady.value = false;
    }
  }

  Future<void> showOfferwall({
    String? placementName,
    TJEntryPoint? entryPoint,
  }) async {
    final name = placementName ?? defaultPlacementName.value;
    await _service.showOfferwall(placementName: name, entryPoint: entryPoint);
    await refreshOfferwallReady(placementName: name);
  }
}